﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using CLibArtreve.bll;
using CLibArtreve.models;

namespace WebAppArtreve.views.shared.components.ratings
{
    public partial class WUCOnlyGlobalRating : System.Web.UI.UserControl
    {
        //VARIABLES
        private Int64 _artId;
        private string _connectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["ARTREVEConnectionString"].ConnectionString;
            }
        }

        //PROPERTIES
        public Int64 ArtId
        {
            get
            {
                return Convert.ToInt64(this.ViewState["ArtId"]);
            }
            set
            {
                _artId = value;
                this.ViewState["ArtId"] = _artId;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {            
        }

        public string GetStarsAllUsers()
        {
            try
            {
                //1. BLL
                //-----------------------
                RatingBLL bllRating = new RatingBLL(_connectionString);

                IList<Rating> listRating;

                _artId = Convert.ToInt64(this.ViewState["ArtId"]);

                listRating = bllRating.GetRatingByArtId(_artId);

                //2. RETURN RATING
                //-----------------------
                if (listRating.Count > 0)
                {
                    //VARIABLES
                    double stars = 0;
                    int i;

                    //COUNT RATING: ALL STARS
                    for (i = 0; i < listRating.Count; i++)
                    {
                        stars += listRating[i].Stars;
                    }

                    //RETURN STARS TO SHOW THEM (AFTER DIVIDING STARS BY NUMBER OF USERS THAT VOTED)
                    return Convert.ToString(Math.Round(stars / i, 2));
                }
                else
                {
                    return "0";
                }

            }
            catch (Exception ex)
            {
                return "0";
                throw (ex);
            }

        }

        protected void lblRating_PreRender(object sender, EventArgs e)
        {
            this.lblRating.Text = GetStarsAllUsers();
        }
    }
}